import {validDataNull} from 'utils/validate';
import website from '@/config/website'

const keyName = website.key + '-';
/**
 * 存储localStorage
 */
export const setStore = (key, value, storeType = {}) => {
    key = keyName + key
    let obj = {
        dataType: typeof (value),
        content: value,
        type: storeType,
        datetime: new Date().getTime()
    }
    if (storeType) {
        window.sessionStorage.setItem(key, JSON.stringify(obj))
        return
    }
    window.localStorage.setItem(key, JSON.stringify(obj))

}
/**
 * 获取localStorage
 */

export const getStore = (key) => {

    key = keyName + key
    let obj = {}
    let content;
    obj = window.sessionStorage.getItem(key);
    if (validDataNull(obj)) {
        obj = window.localStorage.getItem(key)
    }
    if (validDataNull(obj)) {
        return undefined
    }
    try {
        obj = JSON.parse(obj);
    } catch {
        return obj;
    }

    if (obj.dataType === 'string') {
        content = obj.content;
    } else if (obj.dataType === 'number') {
        content = Number(obj.content);
    } else if (obj.dataType === 'boolean') {
        content = eval(obj.content);
    } else if (obj.dataType === 'object') {
        content = obj.content;
    }
    return content;
}
/**
 * 删除localStorage
 */
export const removeStore = (key, storeType) => {

    key = keyName + key
    if (storeType) {
        window.sessionStorage.removeItem(key);
    } else {
        window.localStorage.removeItem(key);
    }

}

/**
 * 获取全部localStorage
 */
export const getAllStore = (storeType) => {
    let list = [];

    if (storeType) {
        for (let i = 0; i <= window.sessionStorage.length; i++) {
            list.push({
                name: window.sessionStorage.key(i),
                content: getStore({
                    name: window.sessionStorage.key(i),
                    type: 'session'
                })
            })
        }
    } else {
        for (let i = 0; i <= window.localStorage.length; i++) {
            list.push({
                name: window.localStorage.key(i),
                content: getStore({
                    name: window.localStorage.key(i),
                })
            })

        }
    }
    return list;

}

/**
 * 清空全部localStorage
 */
export const clearStore = (params = {}) => {
    let {type} = params;
    if (type) {
        window.sessionStorage.clear();
    } else {
        window.localStorage.clear()
    }
}
const store = {
    setStore,
    getStore,
    removeStore,
    getAllStore,
    clearStore
}
export default store
